package net.wanho.ums.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import net.wanho.ums.constant.UserConstant;
import net.wanho.ums.entity.User;
import net.wanho.ums.exception.NameExistsException;
import net.wanho.ums.mapper.UserMapper;
import net.wanho.ums.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Author：汤小洋
 * Date：2023-12-18 16:39
 * Description：<描述>
 */
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Override
    public void register(User user) {
        /**
         * 判断用户名是否存在
         */
        User u = userMapper.selectByName(user.getName());
        if (u != null){
            throw new NameExistsException("用户名已存在！");
        }

        // 设置用户状态默认为启用
        user.setStatus(UserConstant.STATUS_ENABLE);

        userMapper.insert(user);
    }

    @Override
    public void removeById(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public void removeBatch(List<Integer> ids) {
        userMapper.deleteBatch(ids);
    }

    @Override
    public void modify(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void modifyStatus(Integer id, Integer status) {
        userMapper.updateStatusById(id, status);
    }

    @Override
    public List<User> list() {
        return userMapper.selectAll();
    }

    @Override
    public User queryById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public PageInfo<User> queryByPage(Integer pageNum, Integer pageSize, User user) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> users = userMapper.selectByCondition(user);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return pageInfo;
    }
}
